<template>
  <div>
    <van-nav-bar
      title="购物车"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />
    <van-checkbox-group v-model="selGoods" checked-color="#fe4070">
      <van-swipe-cell v-for="(item,index) in goods" :key="index">

        <!-- 当前行 -->
        <van-row>
        <van-col span="2" class="lef-checkbox">
          <van-checkbox :name="item"></van-checkbox>
        </van-col>
        <van-col span="22">
          <van-card
            :price="item.price"
            :title="item.title"
            thumb="https://img01.yzcdn.cn/vant/ipad.jpeg"
          >
            <template #num>
              <van-stepper v-model="item.num" />
            </template>
          </van-card>
        </van-col>
        </van-row>

        <template #right>
          <van-button square text="删除" type="danger" class="delete-button" @click="delGoods(item,index)"/>
        </template>
      </van-swipe-cell>
    </van-checkbox-group>
    

    

    <van-submit-bar :price="total" button-text='去结算' button-color="#fe4070">
  <van-checkbox v-model="sleAll" @click="selAllChange" checked-color="#fe4070">全选</van-checkbox>
  
</van-submit-bar>
  </div>
</template>

<script>
export default {
  data(){
    return{
      sleAll:false,
      total:0,
      goods:[
        {title:'男装',price:200,num:1},
        {title:'女装',price:300,num:1},
        {title:'电脑',price:1000,num:1},
        {title:'玩具',price:50,num:1},
      ],
      selGoods:[] //选中的商品
    }
  },
  watch:{
    selGoods:{
      handler(list){
        //计算总价
        this.total = 0
        list.forEach(item=>{
            this.total += item.price * item.num * 100
        })
        this.sleAll = list.length === this.goods.length && list.length > 0
      }
    }
  },
  methods: {
    selAllChange(){
      if(this.sleAll){
        this.selGoods = this.goods
      }else{
        this.selGoods = []
      }
    },
    delGoods(item,index){
        this.$dialog.confirm({
            message: `确定要删除${item.title}吗?亲!`,
          })
            .then(() => {
              // 删除所有商品中的元素
              this.goods.splice(index,1)

              //删除被选中的元素
              let i = this.selGoods.indexOf(item)
              if(i != -1){
                this.selGoods.splice(i,1)
              }else{

              }
            })
            .catch(() => {
              // on cancel
            });
      },
      onClickLeft(){
        window.history.go(-2);
      }
  },
}
</script>

<style scoped>
html{
  background-color: #f5f5f5;
}
.van-row{
  margin: 20px 0px;
}
.lef-checkbox{
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.delete-button {
  height: 100%;
}

</style>